<template>
	<div class="content-container" v-if="isRouterReady">
		<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
			<el-tab-pane label="购买云手机" name="first">
				<div class="p-6 bg-gray-100 min-h-screen">
					<el-card class="custom-buy-card" shadow="hover" v-loading="loading" style="height: 100%;">
						<el-scrollbar height="63vh" style="padding: 20px 0 20px 20px;">
							<el-form label-width="100px" label-position="top">
								<!-- 							<el-form-item label="设备机型：" class="form-item-left">
								<el-radio-group v-model="form.deviceType">
									<el-radio-button label="标准云机" />
									<el-radio-button label="高端真机" />
								</el-radio-group>
							</el-form-item> -->
								<el-form-item label="Android 版本" class="form-item-left">
									<el-radio-group class="has-gap" v-model="form.androidVersion">
										<el-radio v-for="version in androidVersions" :key="version" border
											:label="'Android ' + version" />
									</el-radio-group>
								</el-form-item>
								<el-form-item label="产品型号：" class="form-item-left">
									<el-radio-group class="has-gap" v-model="form.productModel"
										@change="handleProductChange">
										<el-radio v-for="product in product_types" :key="product.id" border
											:label="product.name" :disabled11="product.instance_count === 0">
											{{ product.name }} - {{ product.description }}
										</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="" class="form-item-left">
									<div>
										<el-tag style="margin-right: 10px; margin-bottom: 5px;"
											v-for="(tag, index) in currentTags" :key="index"
											:type="tagTypes[index % tagTypes.length]" effect="light">
											{{ tag }}
										</el-tag>
									</div>
								</el-form-item>
								<el-form-item label="产品品牌" class="form-item-left">
									<div v-for="(item,index) in phone_type_list" :key="item.brand"
										style="margin-bottom: 10px;margin-right: 10px;">
										<el-button plain :class="item.checked?'phone_type_btn_checked':''"
											@click="change_phone_type(index)">{{item.brand}}</el-button>
									</div>
								</el-form-item>
								<el-form-item label="云机机型" class="form-item-left">
									<el-radio-group class="has-gap" v-model="form.brand_model">
										<el-radio v-for="item in checkedModels" :key="item.id" border
											:label="item.model" :value="item.id">{{ item.model }}
										</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="商品套餐" class="form-item-left">
									<el-radio-group v-model="form.package" class="custom-package-radio"
										@change="calculateTotal">
										<el-radio-button v-for="(pkg,index) in currentPackages" :key="pkg.id"
											:label="pkg.id">
											<div class="package-content">
												<div class="package-days">{{ pkg.name }}</div>
												<div class="package-price">￥{{ pkg.price }}</div>
												<div class="package-discount">原价: ￥{{ (pkg.price * 1.25).toFixed(2) }}
												</div>
											</div>
										</el-radio-button>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="云机参数" class="form-item-left">
									<div style="display: flex;align-items: center;gap: 10px;">
										<span>IP地址</span>
										<el-select v-model="form.is_agency" style="width: 120px;">
											<el-option label="不使用代理" :value="0" @click="agency_change(0)" />
											<el-option label="使用代理" :value="1" @click="agency_change(1)" />
										</el-select>
										<el-popover width="500" content="使用代理将根据代理IP所属地区进行IMEI、手机号、定位、时区等仿真" placement="right">
											<template #reference>
												<p class="question_mark">?</p>
											</template>
										</el-popover>
										<p v-if="form.ProxyId" class="Proxy_info_p">出口IP:{{form.Proxy.host}}
											归属地:{{ form.Proxy.country_code}} - {{form.Proxy.city}}</p>
									</div>
								</el-form-item>
								<el-form-item label="设备数量" class="form-item-left">
									<el-input-number v-model="form.deviceCount" :min="1"
										:max="currentProduct?.instance_count || 1"
										:disabled="!currentProduct || currentProduct.instance_count === 0" />
								</el-form-item>
								<div style="text-align: left;margin-bottom: 10px;">
									<label>自动续费:</label> <el-switch v-model="form.autoRenew" />
								</div>
							</el-form>
						</el-scrollbar>
					</el-card>

					<div class="footer-container">
						<div class="footer-content">
							<span class="balance">账户余额: <b>￥{{balance}}</b></span>
							<div class="total-section">
								<span>总计: <b style="color: #fa5858;font-size: 23px">￥{{ totalPrice }}</b></span>
								<el-button type="warning" size="large" @click="showPaymentDialog"
									:disabled="!currentProduct || currentProduct.instance_count === 0">
									{{ currentProduct?.instance_count === 0 ? '该商品已售罄' : '确认创建' }}
								</el-button>
							</div>
						</div>
					</div>
				</div>
			</el-tab-pane>
			<!-- 保持其他tab内容不变 -->
			<el-tab-pane label="续费云手机" name="second">
				<el-card shadow="hover" class="renew-card" v-loading="renewLoading">
					<el-scrollbar height="63vh" style="padding: 20px 0 20px 20px;">
						<el-row :gutter="20" class="custom-row">
							<el-col :span="12" class="custom-col">
								<!-- 	<el-form-item label="设备机型:" class="form-item-left">
								<el-radio-group v-model="renew_model_radio">
									<el-radio-button label="标准云机" :value="0" />
									<el-radio-button label="高端真机" :value="1" />
								</el-radio-group>
							</el-form-item> -->
								<!-- 修改：将设备ID筛选替换为商品型号筛选 -->
								<el-form-item label="商品型号:" class="form-item-left">
									<el-radio-group class="has-gap" v-model="form.productModel"
										@change="handleProductChange">
										<el-radio v-for="product in product_types" :key="product.id" border
											:label="product.name" :disabled11="product.instance_count === 0">
											{{ product.name }} - {{ product.description }}
										</el-radio>
									</el-radio-group>
								</el-form-item>
								<div style="width: 100%;display:flex;align-items: center">
									<el-form-item label="选择续费设备:" class="form-item-left">
										<el-input v-model="renewSearch" placeholder="输入云手机名称搜索" clearable
											style="width: 240px" />
									</el-form-item>
								</div>
								<!-- 新增：全选控制 -->
								<div class="select-all" style="margin-left: 0; margin-bottom: 10px; text-align: left;">
									<el-checkbox :model-value="selectAllChecked" :indeterminate="selectIndeterminate"
										@change="toggleSelectAll">
										全选 ({{ selectedDevicesCountInCurrentType }}/{{ filteredDevices.length }})
									</el-checkbox>
								</div>
								<div class="device-selection">
									<div class="device-single-col">
										<div v-for="device in filteredDevices" :key="device.id"
											class="device-single-item"
											:class="{ selected: selectedDevices.some(d => d.id === device.id) }"
											@click="toggleDeviceSelection(device)">
											<el-checkbox :model-value="selectedDevices.some(d => d.id === device.id)"
												:disabled="!isDeviceSelectable(device)" />
											<div class="device-info">
												<div class="device-model">{{ device.instances.name }}</div>
												<div class="device-id">名称:{{ device.instance_name }}</div>
												<div class="device-product">型号:
													{{ getProductName(device.instances.product_id) }}
												</div>
												<div class="device-expiry">到期:
													{{ new Date(device.expire_time).toLocaleString() }}
												</div>
											</div>
										</div>
										<div v-if="filteredDevices.length === 0" class="no-devices">
											<el-empty description="没有找到匹配的设备" />
										</div>
									</div>
								</div>
							</el-col>
							<el-divider direction="vertical" />
							<el-col :span="12" class="custom-col">
								<div class="package-selection">
									<el-form-item label="商品套餐:" class="form-item-left">
										<el-radio-group v-model="form.package" class="custom-package-radio"
											@change="calculateTotal">
											<el-radio-button v-for="pkg in renewPackages" :key="pkg.id" :label="pkg.id">
												<div class="package-content">
													<div class="package-days">{{ pkg.name }}</div>
													<div class="package-price">￥{{ pkg.price }}</div>
													<div class="package-discount">时长: {{ pkg.duration }}
														{{ pkg.duration_unit }}
													</div>
												</div>
											</el-radio-button>
										</el-radio-group>
									</el-form-item>
									<el-form-item label="支付方式:" class="form-item-left">
										<el-radio-group class="has-gap" v-model="paymentMethodRenew">
											<el-radio value="balance" size="large" border>
												<div style="display: flex;justify-content: left;align-items: center">
													<span>余额支付</span>
													<span style="margin-left: 10px;color: #666;font-size: 12px">当前余额:
														￥{{ balance }}</span>
												</div>
											</el-radio>
											<el-radio value="alipay" size="large" border>
												<div style="display: flex;justify-content: left;align-items: center">
													<img src="@/assets/alipay.png" alt=""
														style="width: 30px;height: 30px;line-height: 30px;">
													<span>支付宝</span>
												</div>
											</el-radio>
											<el-radio value="wechat" size="large" border>
												<div style="display: flex;justify-content: left;align-items: center">
													<img src="@/assets/weixin.png" style="width: 30px;height: 30px;" />
													<span>微信支付</span>
												</div>
											</el-radio>
										</el-radio-group>
									</el-form-item>
									<el-form-item>
										<div class="auto-renew">
											<el-checkbox v-model="autoRenews">自动续费</el-checkbox>
										</div>
									</el-form-item>
								</div>
							</el-col>
						</el-row>
					</el-scrollbar>
				</el-card>
				<div class="sticky-footer">
					<span class="total">总计:<b>￥{{ calculatedPrice }}</b></span>
					<el-button type="primary" size="large" :disabled="selectedDevices.length === 0"
						:loading="paymentLoading" @click="goRenewResult">
						确认续费
					</el-button>
				</div>
			</el-tab-pane>
		</el-tabs>
		<el-dialog v-model="agency_visible" :width="activeIndex==1?360:720" class="animated-dialog"
			@close="reset_agency_form">
			<template #header="{ close, titleId, titleClass }">
				<div class="my-header flex_between_center">
					<h4 style="margin-top: 0px;margin-bottom: 0px;" :id="titleId" :class="titleClass">
						{{agency_dialog_title}}
					</h4>
				</div>
			</template>
			<div class="proxy-btn-group">
				<div class="btn-container" ref="btnContainer">
					<button v-for="item in agency_slider_list" :key="item.id" class="proxy-btn"
						@click="proxy_btn_change(item)"
						:class="activeIndex==item.id?'check_proxy-btn':''">{{item.name}}</button>
					<div class="slider" :style="sliderStyle" />
				</div>
				<div v-if="activeIndex==1">
					<el-form ref="formRef" :model="add_ruleform" :rules="formRules" style="margin-top: 10px;"
						label-width="80px" :key="activeIndex">
						<el-form-item label="代理类型" prop="protocol">
							<el-select v-model="add_ruleform.protocol" placeholder="请选择代理类型" style="width: 240px;">
								<el-option label="socks5" value="socks5" />
								<el-option label="https" value="https" />
								<el-option label="http" value="http" />
							</el-select>
						</el-form-item>
						<el-form-item label="代理名称" prop="proxy_name">
							<el-input v-model="add_ruleform.proxy_name" clearable style="width: 240px;" />
						</el-form-item>
						<el-form-item label="IP" prop="host">
							<el-input v-model="add_ruleform.host" clearable style="width: 240px;"
								placeholder="例如：192.168.1.1" />
						</el-form-item>
						<el-form-item label="端口" prop="port">
							<el-input v-model="add_ruleform.port" clearable style="width: 240px;"
								placeholder="1-65535" />
						</el-form-item>
						<el-form-item label="账号" prop="user_name">
							<el-input v-model="add_ruleform.user_name" clearable style="width: 240px;" />
						</el-form-item>
						<el-form-item label="密码" prop="password">
							<el-input v-model="add_ruleform.password" clearable style="width: 240px;" />
						</el-form-item>
						<el-form-item label="备注">
							<el-input v-model="add_ruleform.remark" clearable style="width: 240px;" />
						</el-form-item>
						<el-form-item label="">
							<el-button type="primary" link @click="detection_network">网络检测</el-button>
							<el-icon v-if="network_loading" :class="network_loading?'is-loading_icon':''">
								<Loading />
							</el-icon>
						</el-form-item>
					</el-form>
				</div>
				<div v-else>
					<el-input style="margin: 10px 0;" v-model="search_agency_name" placeholder="请输入代理名称">
						<template #suffix>
							<el-icon style="cursor: pointer;" @click="Get_agency_list">
								<Search />
							</el-icon>
						</template>
					</el-input>
					<el-table :data="agency_tableData" class="custom-table" @row-click="agency_row_click"
						:header-cell-style="{textAlign: 'center',backgroundColor: '#f0f3f5',color:'#333'}"
						:cell-style="{ textAlign: 'center'}" height="300">
						<el-table-column label="" width="50">
							<template #default="scope">
								<el-radio v-model="form.ProxyId" :label="scope.row.id" :show-label="false" />
							</template>
						</el-table-column>
						<el-table-column prop="proxy_name" label="代理名称" show-overflow-tooltip />
						<el-table-column prop="remark" label="备注" show-overflow-tooltip />
						<el-table-column prop="status" label="代理状态">
							<template #default="scope">
								<el-tag v-if="scope.row.status==1" type="success">正常</el-tag>
								<el-tag v-else type="danger">异常</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="country_code" label="代理归属" show-overflow-tooltip width="130">
							<template #default="scope">
								<p>{{ scope.row.country_code}} - {{scope.row.city}}</p>
							</template>
						</el-table-column>
						<el-table-column prop="port" label="IP端口" show-overflow-tooltip />
						<el-table-column prop="bind_num" label="已绑云机" show-overflow-tooltip />
					</el-table>
					<div style="width: 100%;margin-top: 10px;display: flex;justify-content: flex-end;">
						<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
							:page-sizes="pagesizes" :background="true" layout="total, sizes, prev, pager, next, jumper"
							:total="agency_tableData_length" @size-change="handleSizeChange"
							@current-change="handleCurrentChange" />
					</div>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="agency_select(false)">取消</el-button>
					<el-button type="primary" @click="agency_select(true)">确认</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 支付弹框 -->
		<el-dialog title="购买云机" v-model="showPayDialog" width="600px" :before-close="handleClosePaymentDialog">
			<div>
				<el-form label-position="top">
					<el-form-item label="产品信息:" class="form-item-left">
						<div
							style="border: 1px solid #ebeef5; border-radius: 4px; padding: 12px; margin-bottom: 16px;width:100%">
							<el-row :gutter="100">
								<el-col :span="24">
									<div class="display-between" style="margin-bottom: 8px;">
										<span style="color: #909399; margin-right: 10px;">产品型号:</span>
										<span>{{ form.productModel }}</span>
									</div>

								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<div class="display-between" style="margin-bottom: 8px;">
										<span style="color: #909399; margin-right: 10px;">Android版本:</span>
										<span>{{ form.androidVersion }}</span>
									</div>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<div class="display-between" style="margin-bottom: 8px;">
										<span style="color: #909399; margin-right: 10px;">设备类型:</span>
										<span>{{ form.deviceType }}</span>
									</div>

								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<div class="display-between" style="margin-bottom: 8px;">
										<span style="color: #909399; margin-right: 10px;">自动续费:</span>
										<span>{{ form.autoRenew ? '是' : '否' }}</span>
									</div>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<div class="display-between" style="margin-bottom: 8px;">
										<span style="color: #909399; margin-right: 10px;">购买时长:</span>
										<span>{{ selectedPackageName }}</span>
									</div>
								</el-col>
								<el-row>
									<el-col :span="24">
										<div class="display-between" style="margin-bottom: 8px;">
											<span style="color: #909399; margin-right: 10px;">设备数量:</span>
											<span>{{ form.deviceCount }}</span>
										</div>
									</el-col>
								</el-row>
							</el-row>
						</div>
					</el-form-item>
					<el-form-item label="订单金额:" class="form-item-left" style="margin-bottom: 15px">
						<!--            <span style="font-size: 14px">订单金额:</span><br>-->
						<!--            <el-input v-model="totalPrice" type="number" disabled><template #prepend>￥</template></el-input>-->
						<span style="color: red;font-weight: bold;font-size: 23px">￥{{totalPrice}}</span>
					</el-form-item>

					<!--          <div style="width: 100%;display: flex;justify-content: left;margin: 15px 0;">-->
					<!--            <span style="font-size: 14px">支付方式:</span>-->
					<!--          </div>-->

					<el-form-item label="支付方式:" class="form-item-left" style="margin-bottom: 15px">
						<el-radio-group class="has-gap" v-model="paymentMethod">
							<el-radio value="balance" size="large" border>
								<div style="display: flex;justify-content: left;align-items: center">
									<!--                  <img src="@/assets/balance.png" alt="" style="width: 30px;height: 30px;line-height: 30px;">-->
									<span>余额支付</span>
									<span style="margin-left: 10px;color: #666;font-size: 12px">当前余额:
										￥{{ balance }}</span>
								</div>
							</el-radio>
							<el-radio value="alipay" size="large" border>
								<div style="display: flex;justify-content: left;align-items: center">
									<img src="@/assets/alipay.png" alt=""
										style="width: 30px;height: 30px;line-height: 30px;">
									<span>支付宝</span>
								</div>
							</el-radio>
							<el-radio value="wechat" size="large" border>
								<div style="display: flex;justify-content: left;align-items: center">
									<img src="@/assets/weixin.png" style="width: 30px;height: 30px;" />
									<span>微信支付</span>
								</div>
							</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
			</div>
			<div style="width: 100%;">
				<el-button style="width:100%;" type="primary" @click="handlePayment"
					:loading="paymentLoading">确认支付</el-button>
			</div>
		</el-dialog>
		<!-- QR Code Payment Dialog (与钱包页面相同) -->
		<el-dialog :title="qrDialogTitle" v-model="showQrDialog" width="400px" :close-on-click-modal="false"
			:close-on-press-escape="false" :show-close="false">
			<div style="text-align: center">
				<div v-if="paymentStatus === 'pending'">
					<div v-if="paymentMethod === 'wechat'">
						<div ref="qrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;"></div>
						<p style="color: #666; margin-bottom: 20px;">请使用微信扫描二维码完成支付</p>
					</div>
					<div v-else-if="paymentMethod === 'alipay'">
						<div ref="qrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;"></div>
						<p style="color: #666; margin-bottom: 20px;">请使用支付宝扫描二维码完成支付</p>
					</div>
					<el-button type="primary" @click="checkPaymentStatus" :loading="checkingPayment">我已支付</el-button>
					<el-button @click="cancelPayment">取消支付</el-button>
				</div>
				<div v-else-if="paymentStatus === 'success'" style="color: #67C23A">
					<el-icon size="50px">
						<CircleCheck />
					</el-icon>
					<p style="font-size: 18px; margin-top: 10px;">支付成功</p>
					<p style="color: #666; margin-top: 10px;">支付金额: ￥{{ totalPrice }}</p>
					<el-button type="primary" style="margin-top: 20px;" @click="skip_myphone">确定</el-button>
				</div>
				<div v-else-if="paymentStatus === 'failed'" style="color: #F56C6C">
					<el-icon size="50px">
						<CircleClose />
					</el-icon>
					<p style="font-size: 18px; margin-top: 10px;">支付失败</p>
					<p style="color: #666; margin-top: 10px;">{{ paymentError }}</p>
					<div style="margin-top: 20px;">
						<el-button type="primary" @click="retryPayment">重试</el-button>
						<el-button @click="closeQrDialog">取消</el-button>
					</div>
				</div>
			</div>
		</el-dialog>
		<el-dialog :title="qrDialogTitle" v-model="showRenewQrDialog" width="400px" :close-on-click-modal="false"
			:close-on-press-escape="false" :show-close="false">
			<div style="text-align: center">
				<div v-if="paymentStatus === 'pending'">
					<div v-if="paymentMethodRenew === 'wechat'">
						<div ref="renewQrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;">
						</div>
						<p style="color: #666; margin-bottom: 20px;">请使用微信扫描二维码完成支付</p>
					</div>
					<div v-else-if="paymentMethodRenew === 'alipay'">
						<div ref="renewQrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;">
						</div>
						<p style="color: #666; margin-bottom: 20px;">请使用支付宝扫描二维码完成支付</p>
					</div>
					<el-button type="primary" @click="checkPaymentStatus" :loading="checkingPayment">我已支付</el-button>
					<el-button @click="cancelRenewPayment">取消支付</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		useRoute
	} from 'vue-router'
	import {
		ref,
		computed,
		onMounted,
		watch,
		nextTick,
		onUnmounted,
		defineProps,
		getCurrentInstance
	} from 'vue'
	import QRCode from 'qrcodejs2'
	import {
		CircleCheck,
		CircleClose
	} from '@element-plus/icons-vue'
	import {
		ElMessage
	} from 'element-plus'
	import request from '@/utils'
	import {
		useRouter
	} from "vue-router";
	const appRouter = getCurrentInstance()?.appContext.config.globalProperties.$router
	// 其他变量定义保持不变
	const route = useRoute()
	const props = defineProps({
		id: {
			type: String,
			default: '0'
		}
	})
	const qrCodeRef = ref(null)
	const loading = ref(true)
	const products = ref([])
	const androidVersions = ref([])
	const tagTypes = ['success', 'info', 'warning', 'danger']
	const balance = ref(0)
	const showPayDialog = ref(false)
	const showQrDialog = ref(false)
	const showRenewQrDialog = ref(false)
	const paymentMethod = ref('balance')
	const paymentMethodRenew = ref('balance')
	const paymentLoading = ref(false)
	const paymentStatus = ref('pending')
	const paymentError = ref('')
	const checkingPayment = ref(false)
	const qrDialogTitle = ref('')
	const qrCode = ref(null)
	const paymentCheckInterval = ref(null)
	const currentOrderId = ref('')
	const router = useRouter()
	const renewSearch = ref('')
	const deviceIdFilter = ref('') // 新增：设备ID筛选
	const selectAllDevices = ref(false)
	const selectedPackages = ref(1)
	const autoRenews = ref(true)
	const selectedDevices = ref([])
	const renew_model_radio = ref(0) //续费选择设备机型(虚拟机还是真机)
	const phone_type_list = ref([])
	const renewPackages = ref([]) // 续费套餐列表
	const currentPackagePrice = computed(() => {
		const pkg = renewPackages.value.find(p => p.id === form.value.package)
		return pkg ? Number(pkg.price) : 0
	})
	const calculatedPrice = computed(() => {
		const count = selectedDevices.value.length
		return (currentPackagePrice.value * count).toFixed(2)
	})
	const renewLoading = ref(false) // 加载状态
	// 设备列表数据
	const devices = ref([])
	const selectedProductType = ref(null) // 选中的产品类型ID
	const selectedProductTypes = ref([])
	const availableProducts = ref([]) // 所有可用的产品类型
	const product_types = ref([]) // 当前设备机型所配对的产品型号和套餐
	const renewQrCodeRef = ref(null)
	const renewQrCode = ref(null)
	const activeIndex = ref(2);
	const agency_visible = ref(false) //使用代理配置下弹出弹框开关
	const agency_dialog_title = ref('选择代理') //使用代理配置下弹出弹框开关
	const agency_slider_list = ref([{
		name: '添加新代理',
		id: 1
	}, {
		name: '选择代理',
		id: 2
	}]) //代理弹窗滑块数组
	const btnContainer = ref(null);
	const check_radio_agency = ref()
	const btnWidth = ref(0);
	const agency_tableData = ref([]);
	const search_agency_name = ref('');
	const currentPage = ref(1);
	const pagesizes = ref([10, 20, 30, 50, 100, 200]);
	const pageSize = ref(10);
	const agency_tableData_length = ref(0);
	const form = ref({
		androidVersion: '',
		deviceType: '高端真机',
		productModel: '',
		package: null,
		autoRenew: true,
		deviceCount: 1,
		brand_model: null,
		is_agency: 0,
		ProxyId: null,
		Proxy: null
	})
	const formRef = ref(); // 代理表单引用
	const network_loading = ref(false)
	const agency_vloading = ref(false)
	const add_ruleform = ref({ //添加代理表单数据
		proxy_name: '',
		protocol: '',
		host: '',
		port: '',
		user_name: '',
		password: '',
		remark: ''
	})
	// 表单验证规则
	const formRules = {
		protocol: [{
			required: true,
			message: '请选择代理类型',
			trigger: 'change'
		}],
		proxy_name: [{
				required: true,
				message: '请输入代理名称',
				trigger: 'blur'
			},
			{
				min: 1,
				max: 15,
				message: '代理名称长度在 1 到 15 个字符',
				trigger: 'blur'
			}
		],
		host: [{
				required: true,
				message: '请输入IP地址',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('请输入IP地址'));
						return;
					}
					// IPv4 地址验证正则表达式
					const ipv4Regex =
						/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

					if (!ipv4Regex.test(value)) {
						callback(new Error('请输入有效的IPv4地址（例如：192.168.1.1）'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		port: [{
				required: true,
				message: '请输入端口号',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('请输入端口号'));
						return;
					}
					// 检查是否为数字且没有小数点
					const portNumber = Number(value);
					if (isNaN(portNumber) || !Number.isInteger(portNumber)) {
						callback(new Error('端口号必须是整数'));
						return;
					}
					// 检查端口范围 (1-65535)
					if (portNumber < 1 || portNumber > 65535) {
						callback(new Error('端口号必须在 1-65535 范围内'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		user_name: [{
			min: 0,
			max: 50,
			message: '账号长度不能超过 50 个字符',
			trigger: 'blur'
		}],
		password: [{
			min: 0,
			max: 50,
			message: '密码长度不能超过 50 个字符',
			trigger: 'blur'
		}]
	};
	//计算代理弹窗滑块宽度
	const sliderStyle = computed(() => ({
		transform: `translateX(${activeIndex.value * btnWidth.value}px)`,
		width: `${btnWidth.value}px`
	}));
	// 计算用户拥有的产品类型
	const userProducts = computed(() => {
		if (!Array.isArray(devices.value)) return []
		const productIds = new Set()
		devices.value.forEach(device => {
			if (device && device.instances && device.instances.product_id) {
				productIds.add(device.instances.product_id)
			}
		})
		return Array.from(productIds)
	})
	// 获取所有产品类型
	const fetchAllProducts = async () => {
		try {
			const response = await request.get('/products/list')
			if (response.data.code === 200 && response.data.data && response.data.data.ProductsList) {
				availableProducts.value = response.data.data.ProductsList
			} else {
				availableProducts.value = []
			}
		} catch (error) {
			console.error('获取产品列表失败:', error)
			availableProducts.value = []
		}
	}

	//全选筛选同一商品型号选中的设备
	const selectedDevicesCountInCurrentType = computed(() => {
		if (!selectedProductType.value) {
			return selectedDevices.value.length;
		}
		return selectedDevices.value.filter(device =>
			device.instances.product_id === selectedProductType.value
		).length;
	});
	//获取所有产品品牌
	const get_product_brand = () => {
		const response = request.get('/realphone/list')
		response.then((res) => {
			phone_type_list.value = res.data.data.map((item, index) => ({
				...item,
				checked: index === 0 // 第一个元素默认选中
			}));
			form.value.brand_model = phone_type_list.value[0].models[0].id
		}).catch(() => {})

	}
	//选中产品品牌
	const change_phone_type = (ind) => {
		phone_type_list.value = phone_type_list.value.map((item, index) => ({
			...item,
			checked: index === ind // 只有当前索引项选中
		}));
		if (checkedModels.value.length > 0) {
			form.value.brand_model = checkedModels.value[0].id
		} else {
			ElMessage.warning('该品牌暂时没有机型')
		}
	}
	//代理功能滑块点击
	const proxy_btn_change = (item) => {
		activeIndex.value = item.id
		agency_dialog_title.value = item.name
		reset_agency_form()
	}
	//购买云机时是否使用代理
	const agency_change = (val) => {
		if (btnContainer.value) {
			// 获取容器内第一个按钮的宽度（假设三个按钮宽度相同）
			const buttons = btnContainer.value.querySelectorAll('.proxy-btn');
			if (buttons.length) {
				btnWidth.value = buttons[0].offsetWidth;
			}
		}
		if (val == 0) {
			form.value.Proxy = null
			form.value.ProxyId = null
		} else {
			agency_visible.value = true
			Get_agency_list()
		}
	}
	//获取代理列表
	const Get_agency_list = () => {
		var params = ``
		if (search_agency_name.value) {
			params += `&name=${search_agency_name.value}`
		}
		request.get(`/proxy/list?page=${currentPage.value}&pageSize=${pageSize.value}` + params).then((res) => {
			agency_tableData.value = res.data.data;
			agency_tableData_length.value = res.data.total
		});
	}
	// 验证并提交表单
	const validateAndSubmit = async () => {
		if (!formRef.value) return;
		agency_vloading.value = true
		try {
			await formRef.value.validate();
			await add_agency_commit();
		} catch (error) {
			agency_vloading.value = false
			ElMessage.error('请检查添加代理表单填写是否正确');
		}
	}
	//添加代理
	const add_agency_commit = async () => {
		try {
			const {
				port,
				user_name,
				proxy_name,
				...rest
			} = add_ruleform.value;
			const requestData = { //不同字段进行转接
				...rest,
				port: Number(port),
				username: user_name,
				name: proxy_name
			};
			const response = await request.post('/proxy/create', requestData);
			if (response.data.code === 200) {
				ElMessage.success('代理添加成功');
				agency_vloading.value = false
				activeIndex.value = 2
				await Get_agency_list();
			} else {
				agency_vloading.value = false
			}
		} catch (error) {
			agency_vloading.value = false
		}
	}
	//重置代理表单数据
	const reset_agency_form = () => {
		add_ruleform.value = JSON.parse(JSON.stringify({
			proxy_name: '',
			protocol: '',
			host: '',
			port: '',
			user_name: '',
			password: '',
			remark: ''
		}))
	}
	//添加代理网络检测
	const detection_network = async () => {
		if (!formRef.value) return;
		try {
			// 只验证必要的字段
			await formRef.value.validateField(['protocol', 'proxy_name', 'host', 'port']);
			network_loading.value = true
			const {
				port,
				user_name,
				proxy_name,
				...rest
			} = add_ruleform;
			const requestData = { //不同字段进行转接
				...rest,
				port: Number(port),
				username: user_name,
				name: proxy_name
			};
			const response = await request.post('/proxy/detectip', requestData);
			if (response.data.code === 200) {
				network_loading.value = false
				ElMessage.success(`网络检测成功: 连接正常`);
			} else {
				ElMessage.error(response.data.msg || '网络检测失败');
				network_loading.value = false
			}
		} catch (error) {
			network_loading.value = false
		}
	}
	//代理列表单行点击
	const agency_row_click = (row) => {
		form.value.Proxy = row
		form.value.ProxyId = row.id
	}
	//代理弹窗确认
	const agency_select = (flag) => {
		if (flag) {
			if (activeIndex.value == 1) {
				validateAndSubmit()
			} else {
				if (!flag) {
					form.value.Proxy = null
					form.value.ProxyId = null
				}
				if (!form.value.ProxyId) {
					form.value.is_agency = 0
				}
				reset_agency_form() //重置代理表单
				agency_visible.value = false
			}
		} else {
			reset_agency_form() //重置代理表单
			agency_visible.value = false
		}
	}
	//代理分页器的每页数据数量
	const handleSizeChange = (val) => {
		pageSize.value = val
		Get_agency_list()
	}
	//代理获取分页器当前页
	const handleCurrentChange = (val) => {
		currentPage.value = val
		Get_agency_list()
	}
	//计算返回产品品牌下的机型数组
	const checkedModels = computed(() => {
		// 若phone_type_list为空或不是数组，返回空数组
		if (!phone_type_list.value || !phone_type_list.value.length) return [];
		// 找到checked为true的对象（只会有一个）
		const checkedItem = phone_type_list.value.find(item => item.checked);
		// 存在则返回其models数组，否则返回空数组
		return checkedItem ? checkedItem.models : [];
	});
	// 检查用户是否拥有某产品
	const userHasProduct = (productId) => {
		if (!Array.isArray(userProducts.value)) return false
		return userProducts.value.includes(productId)
	}

	// 判断某台设备是否可选（复用上面的 userHasProduct）
	const isDeviceSelectable = (device) => {
		return userHasProduct(device.instances.product_id)
	}

	// 根据产品类型筛选设备
	const filterByProductType = () => {
		if (selectedProductType.value) {
			fetchRenewPackages(selectedProductType.value)
		} else {
			renewPackages.value = []
			form.value.package = null
		}
	}
	// 获取产品名称
	const getProductName = (productId) => {
		// 防御性判断 availableProducts.value 是否为数组
		if (!Array.isArray(availableProducts.value)) return '未知型号'
		const product = availableProducts.value.find(p => p.id === productId)
		return product ? product.name.substring(0, 2) : '未知型号'
	}
	const selectedDevicesCount = computed(() => selectedDevices.value.length)
	// 根据产品类型筛选设备
	const filteredDevices = computed(() => {
		let filtered = devices.value.filter(device => userHasProduct(device.instances.product_id));
		if (selectedProductType.value) {
			filtered = filtered.filter(device => device.instances.product_id === selectedProductType.value);
		}
		if (renewSearch.value) {
			filtered = filtered.filter(device => device.instances.name.includes(renewSearch.value) || device.id
				.toString().includes(renewSearch.value)
			);
		}
		return filtered;
	});
	const activeName = ref('first')
	const totalPrice = ref(0)
	const currentProduct = computed(() => {
		return product_types.value.find(p => p.name === form.value.productModel)
	})
	const currentTags = computed(() => {
		if (!currentProduct.value) return []
		return currentProduct.value.tags.split(',')
	})

	const currentPackages = computed(() => {
		if (!currentProduct.value) return []
		return currentProduct.value.product_packages
	})
	const fetchProducts = async () => {
		try {
			const response = await request.get('/products/list')
			products.value = response.data.data.ProductsList
			product_types.value = response.data.data.ProductsList
			androidVersions.value = response.data.data.AndroidVersions
			if (androidVersions.value.length > 0) {
				form.value.androidVersion = `Android ${androidVersions.value[0]}`
			}
			if (products.value.length > 0) {
				form.value.productModel = products.value[0].name
				if (products.value[0].product_packages.length > 0) {
					form.value.package = products.value[0].product_packages[0].id
				}
			}
			calculateTotal()
		} catch (error) {} finally {
			loading.value = false
		}
	}

	const fetchBalance = async () => {
		try {
			const token = localStorage.getItem('token');
			if (token) {
				const response = await request.get('/user/profile')
				if (response.data.code === 200) {
					balance.value = response.data.data.balance
				}
			} else {
				balance.value = 0
			}

		} catch (error) {
			console.error('Error fetching balance:', error)
		}
	}
	//点击产品型号
	const handleProductChange = () => {
		if (currentPackages.value.length > 0) {
			form.value.package = currentPackages.value[0].id
		}
		form.value.deviceCount = 1
		calculateTotal()
	}

	const calculateTotal = () => {
		if (!form.value.package) {
			totalPrice.value = 0
			return
		}

		const selectedPackage = currentPackages.value.find(pkg => pkg.id === form.value.package)
		if (selectedPackage) {
			totalPrice.value = (selectedPackage.price * form.value.deviceCount).toFixed(2)
		} else {
			totalPrice.value = 0
		}
	}

	const showPaymentDialog = () => {
		showPayDialog.value = true
	}

	const handlePayment = async () => {
		if (!paymentMethod.value) {
			ElMessage.error('请选择支付方式')
			return
		}
		paymentLoading.value = true
		try {
			// 准备请求数据
			const requestData = {
				product_id: currentProduct.value.id, // 产品型号ID
				android_version: form.value.androidVersion.replace('Android ', ''), // 安卓版本（去掉"Android "前缀）
				package_id: form.value.package, // 商品套餐ID
				quantity: form.value.deviceCount, // 购买设备数量
				payment_source: paymentMethod.value, // 支付方式
				amount: totalPrice.value, // 支付金额
				real_phone_model_id: form.value.brand_model, //机型id
				auto_renew: form.value.autoRenew, // 自动续费状态
				ProxyId: form.value.ProxyId
			}
			if (form.value.deviceType == '高端真机') {
				const checkedItem = phone_type_list.value.find(item => item.checked === true);
				requestData.brand = checkedItem.brand
			}
			// 余额支付
			if (paymentMethod.value === 'balance') {
				if (parseFloat(balance.value) < parseFloat(totalPrice.value)) {
					ElMessage.error('余额不足，请选择其他支付方式')
					return
				}
				const response = await request.post('/products/payment', requestData)
				if (response.data.code === 200) {
					ElMessage.success('支付成功')
					showPayDialog.value = false
					fetchBalance() // 刷新余额
					appRouter?.push('/my_phone')
				} else {
					ElMessage.error(response.msg || '支付失败')
				}
			} else {
				// 微信/支付宝支付
				const response = await request.post('/products/payment', requestData)
				if (response.data.code === 200) {
					// 根据返回的 result_type 处理不同的支付方式
					if (response.data.data.result_type === 'url') {
						// 跳转到第三方支付页面
						window.location.href = response.data.data.data
					} else if (response.data.data.result_type === 'qrcode_str') {
						// 显示二维码支付弹窗
						showPayDialog.value = false
						qrDialogTitle.value = paymentMethod.value === 'wechat' ? '微信支付' : '支付宝支付'
						currentOrderId.value = response.data.data.order_id
						setTimeout(() => {
							showQrDialog.value = true
						}, 900);
						setTimeout(() => {
							initQRCode(response.data.data.data) // 初始化二维码
						}, 1000);
						startPaymentStatusCheck() // 开始轮询检查支付状态
					} else {
						ElMessage.error('未知的支付返回类型')
					}
				}
			}
		} catch (error) {

		} finally {
			paymentLoading.value = false
		}
	}

	const initQRCode = (qrData) => {
		try {
			// 清除旧二维码
			if (qrCode.value) {
				qrCode.value.clear();
				qrCode.value = null;
			}
			// 清空容器
			qrCodeRef.value.innerHTML = '';
			// 生成新二维码
			qrCode.value = new QRCode(qrCodeRef.value, {
				text: qrData,
				width: 200,
				height: 200,
				colorDark: "#000000",
				colorLight: "#ffffff",
				correctLevel: QRCode.CorrectLevel.H
			});
		} catch (e) {
			// 备用方案：直接跳转
			window.location.href = qrData;
		}
	};

	const startPaymentStatusCheck = () => {
		stopPaymentStatusCheck()
		paymentCheckInterval.value = setInterval(() => {
			checkPaymentStatus(false)
		}, 5000)
	}

	const stopPaymentStatusCheck = () => {
		if (paymentCheckInterval.value) {
			clearInterval(paymentCheckInterval.value)
			paymentCheckInterval.value = null
		}
	}

	const checkPaymentStatus = async (showLoading = true) => {
		if (showLoading) checkingPayment.value = true

		try {
			const response = await request.get(`/order/status?orderId=${currentOrderId.value}`)
			if (response.data.code === 200) {
				const status = response.data.data.
				status
				if (status === 'success') {
					paymentStatus.value = 'success'
					stopPaymentStatusCheck()
					// setTimeout(() => {
					// 	router
					// 		.push('/my_phone')
					// }, 2000)
					fetchBalance() // 刷新余额
					fetchDevices() // 刷新设备列表
					showRenewQrDialog.value = false
				} else if (status === 'failed') {
					paymentStatus.value = 'failed'
					paymentError.value = response.data.data.message || '支付失败'
					stopPaymentStatusCheck()
				}
			} else {
				paymentStatus.value = 'failed'
				paymentError.value = response.msg || '支付状态检查失败'
				stopPaymentStatusCheck()
			}
		} catch (error) {
			paymentStatus.value = 'failed'
			paymentError.value = '支付状态检查失败: ' + (error.response?.data?.msg || error.message)
			stopPaymentStatusCheck()
		} finally {
			checkingPayment.value = false
		}
	}

	const cancelPayment = () => {
		stopPaymentStatusCheck()
		showQrDialog.value = false
		paymentStatus.value = 'pending'
		ElMessage('支付已取消')
	}
	const cancelRenewPayment = () => {
		stopPaymentStatusCheck()
		showRenewQrDialog.value = false
		paymentStatus.value = 'pending'
		ElMessage('支付已取消')
	}
	//支付完成后点击确认按钮,关闭弹窗并跳转到:我的云手机页面
	const skip_myphone = () => {
		showQrDialog.value = false
		paymentStatus.value = 'pending'
		paymentError.value = ''
		appRouter?.push('/my_phone')
	}
	const closeQrDialog = () => {
		showQrDialog.value = false
		paymentStatus.value = 'pending'
		paymentError.value = ''
	}
	const closeReQrDialog = () => {
		showRenewQrDialog.value = false
		paymentStatus.value = 'pending'
		paymentError.value = ''
	}

	const retryPayment = () => {
		paymentStatus.value = 'pending'
		handlePayment()
	}

	const handleClosePaymentDialog = (done) => {
		if (paymentLoading.value) {
			ElMessage.warning('正在处理支付，请稍候')
			return false
		}
		done()
	}
	const isRouterReady = ref(false)

	onMounted(() => {
		fetchProducts();
		fetchBalance();
		fetchDevices();
		fetchAllProducts();
		get_product_brand()
		try {
			isRouterReady.value = true;
			// 解析props中的参数
			const parsedProps = JSON.parse(JSON.stringify(props));
			const skipValue = parsedProps.id;
			// 检查是否是默认值或空值
			if (skipValue && skipValue !== '0') {
				// 解析传递的参数
				const parsedParams = JSON.parse(decodeURIComponent(skipValue));
				// 设置tab
				activeName.value = parsedParams.tab || 'second';
				renew_model_radio.value = parsedParams.is_realphone
				// 监听devices数据加载完成
				watch(devices, (newDevices) => {
					if (newDevices.length > 0) {
						// 处理设备选中逻辑
						if (parsedParams.deviceId && parsedParams.deviceId.length > 0) {
							// 筛选出选中的设备
							selectedDevices.value = newDevices.filter(d =>
								parsedParams.deviceId.includes(Number(d.id))
							);
							// 如果有选中的设备，设置对应的商品型号
							if (selectedDevices.value.length > 0) {
								// 获取第一个选中设备的商品型号
								const productId = selectedDevices.value[0].instances.product_id;
								selectedProductType.value = productId;
								// 获取对应的套餐
								fetchRenewPackages(productId);
							}
						}
					}
				}, {
					immediate: true
				});
			} else {
				// 处理没有传递设备ID的情况
				activeName.value = 'first';
			}
		} catch (error) {
			console.error('参数解析错误:', error);
			// 可以在这里添加错误处理或重定向逻辑
			ElMessage.error('参数解析错误，请返回重新选择设备');
			activeName.value = 'first';
		}
	});
	watch(() => form.value.deviceCount, calculateTotal)
	// 组件卸载时清除定时器
	onUnmounted(() => {
		stopPaymentStatusCheck()
		if (qrCode.value) {
			try {
				qrCode.value.clear()
			} catch (e) {
				console.error('Error clearing QRCode:', e)
			}
			qrCode.value = null
		}
	})
	// 计算选中的套餐名称
	const selectedPackageName = computed(() => {
		if (!form.value.package) return ''
		const pkg = currentPackages.value.find(p => p.id === form.value.package)
		return pkg ? pkg.name : ''
	})

	// 方法
	const toggleDeviceSelection = (device) => {
		const idx = selectedDevices.value.findIndex(d => d.id === device.id);
		if (idx > -1) {
			selectedDevices.value.splice(idx, 1);
		} else {
			selectedDevices.value.push(device);
		}
		// 更新全选状态
		selectAllChecked.value = selectedDevices.value.filter(d =>
			filteredDevices.value.some(fd => fd.id === d.id)
		).length === filteredDevices.value.length;

		selectIndeterminate.value =
			selectedDevices.value.filter(d =>
				filteredDevices.value.some(fd => fd.id === d.id)
			).length > 0 &&
			selectedDevices.value.filter(d =>
				filteredDevices.value.some(fd => fd.id === d.id)
			).length < filteredDevices.value.length;

		// 套餐：只要还剩设备就取第一台型号，一台都没有就清空
		if (selectedDevices.value.length) {
			fetchRenewPackages(selectedDevices.value[0].instances.product_id);
		} else {
			renewPackages.value = [];
			form.value.package = null;
		}
	}

	const toggleSelectAll = (checked) => {
		if (checked) {
			// 只添加当前过滤列表中的设备
			const newSelected = [...filteredDevices.value];
			selectedDevices.value = newSelected;
		} else {
			// 只移除当前过滤列表中的设备
			selectedDevices.value = selectedDevices.value.filter(
				device => !filteredDevices.value.some(d => d.id === device.id)
			);
		}
	}

	watch(filteredDevices, () => {
		selectAllChecked.value = selectedDevices.value.length === filteredDevices.value.length;
		selectIndeterminate.value = selectedDevices.value.length > 0 && selectedDevices.value.length <
			filteredDevices.value.length;
	});

	const selectAllChecked = computed(() => {
		if (filteredDevices.value.length === 0) return false;
		return filteredDevices.value.every(device => selectedDevices.value.some(d => d.id === device.id));
	});

	const selectIndeterminate = computed(() => {
		const selectedCount = filteredDevices.value.filter(device => selectedDevices.value.some(d => d.id ===
			device.id)).length;
		return selectedCount > 0 && selectedCount < filteredDevices.value.length;
	});

	const fetchDevices = async () => {
		try {
			renewLoading.value = true
			const response = await request.get('/containers/list')
			if (response.data.code === 200) {
				devices.value = response.data.data.map(item => ({
					...item,
					selected: false
				}))
			}
		} catch (error) {} finally {
			renewLoading.value = false
		}
	}

	// 获取续费套餐
	const fetchRenewPackages = async (productId) => {
		try {
			renewLoading.value = true
			const response = await request.get(`/products/packages?product_id=${productId}`)
			if (response.data.code === 200) {
				renewPackages.value = response.data.data.product_packages
				if (renewPackages.value.length > 0) {
					form.value.package = renewPackages.value[0].id
				}
			}
		} catch (error) {
			ElMessage.error('获取套餐信息失败: ' + error.message)
		} finally {
			renewLoading.value = false
		}
	}

	// 处理续费
	const goRenewResult = async () => {
		// 1. 基础必填项验证
		if (!selectedDevices.value?.length) {
			ElMessage.error('请至少选择一台设备');
			return;
		}
		if (!form.value.package) {
			ElMessage.error('请选择续费套餐');
			return;
		}
		if (!paymentMethodRenew.value) {
			ElMessage.error('请选择支付方式');
			return;
		}

		// 2. 余额支付专属检查（关键修改：在发送请求前检查）
		if (paymentMethodRenew.value === 'balance') {
			const currentBalance = Number(balance.value) || 0;
			const needPay = Number(calculatedPrice.value) || 0;

			if (currentBalance < needPay) {
				ElMessage.error(`余额不足,请选择其他支付方式`);
				return; // 完全阻止后续请求
			}
		}

		paymentLoading.value = true;

		try {
			// 3. 准备请求数据（此时余额一定充足）
			const requestData = {
				instance_use_ids: selectedDevices.value.map(device => device.id), // 处理多个设备
				package_id: form.value.package,
				payment_source: paymentMethodRenew.value,
				auto_renew: autoRenews.value
			};

			// 4. 调用续费接口
			const response = await request.post('/containers/renew', requestData);

			// 5. 处理成功响应
			if (response.data.code === 200) {
				const {
					data,
					order_id,
					result_type
				} = response.data.data;
				currentOrderId.value = order_id;

				// 余额支付成功处理
				if (paymentMethodRenew.value === 'balance') {
					ElMessage.success('续费成功');
					fetchBalance(); // 刷新余额显示
					appRouter?.push('/my_phone')
				}
				// 第三方支付处理
				else if (result_type === 'url') {
					window.location.href = data;
				} else if (result_type === 'qrcode_str') {
					showRenewQrDialog.value = true;
					qrDialogTitle.value = paymentMethodRenew.value === 'wechat' ?
						'微信支付' :
						'支付宝支付';

					await nextTick();
					initRenewQRCode(data);
					startPaymentStatusCheck();
				}
			}
		} catch (error) {
			// 6. 错误处理（此时不会收到余额不足错误）
			console.error('续费异常:', error);

			let errorMessage = '续费失败';
			if (error.response?.status === 401) {
				errorMessage = '登录已过期，请重新登录';
			} else if (error.response?.data?.msg) {
				errorMessage = error.response.data.msg;
			} else if (error.message.includes('Network Error')) {
				errorMessage = '网络连接失败，请检查网络';
			}

			ElMessage.error(errorMessage);
			showQrDialog.value = false;
		} finally {
			paymentLoading.value = false;
		}
	};

	const initRenewQRCode = (qrData) => {
		try {
			// 清除旧二维码
			if (renewQrCode.value) {
				renewQrCode.value.clear();
				renewQrCode.value = null;
			}

			// 清空容器
			renewQrCodeRef.value.innerHTML = '';

			// 生成新二维码
			renewQrCode.value = new QRCode(renewQrCodeRef.value, {
				text: qrData,
				width: 200,
				height: 200,
				colorDark: "#000000",
				colorLight: "#ffffff",
				correctLevel: QRCode.CorrectLevel.H
			});
		} catch (e) {
			console.error('二维码生成失败:', e);
			window.location.href = qrData;
		}
	};

	watch(selectAllDevices, (val) => {
		devices.value.forEach(device => {
			device.selected = val
		})
	})

	watch(selectedDevicesCount, (count) => {
		if (count === devices.value.length) {
			selectAllDevices.value = true
		} else if (count === 0) {
			selectAllDevices.value = false
		}
	})
</script>
<script>
	export default {
		name: "PurchesPage",
	}
</script>
<style lang="less" scoped>
	.is-loading_icon {
		animation: rotating 2s linear infinite;
	}

	@keyframes rotating {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.Proxy_info_p {
		padding: 0px 10px;
		border-radius: 10px;
		background-color: #f2f8fe;
		color: #0079f2;
	}

	.question_mark {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background-color: #e6f2fe;
		color: #2f91f4;
		line-height: 20px;
		font-weight: 900;
		text-align: center;
		cursor: pointer;
	}

	.custom-table {
		width: 100%;
	}

	:deep(.custom-table .el-table__header-wrapper) {
		border-radius: 10px 10px 0 0;
		border-top: 2px solid #eaecee;
		border-left: 2px solid #eaecee;
		border-right: 2px solid #eaecee;
		border-bottom: none;
		box-sizing: border-box;
	}

	/deep/ .el-table .el-radio__label {
		display: none;
	}

	.proxy-btn-group {
		text-align: left;
		margin-bottom: 10px;
	}

	.btn-container {
		position: relative;
		display: inline-flex;
		border: 1px solid #d1d3d4;
		border-radius: 8px;
		overflow: hidden;
		background-color: #e4e5e7;
	}

	.proxy-btn {
		padding: 10px 24px;
		background: transparent;
		border: none;
		color: #a2a5ab;
		cursor: pointer;
		font-size: 14px;
		font-weight: 500;
		z-index: 1;
		transition: all 0.5s;
		border-radius: 8px;
	}

	.check_proxy-btn {
		color: #1890ff;
		background-color: #fff;
	}

	.slider {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		background: #409eff;
		transition: transform 0.3s ease;
		border-radius: 7px;
	}

	:deep(.el-card__body) {
		padding: 0px;
	}

	:deep(.el-divider--vertical) {
		height: auto !important;
		margin: 0 16px;
	}

	.custom-row {
		width: 100%;

	}

	:deep(.custom-row .el-col-12) {
		flex: 0 0 calc(50% - 18px);
		max-width: calc(50% - 18px);
		;
	}

	.custom-divider {
		width: 1px;
		margin: 0 10px;
		height: 100%;
	}

	/* 确保父容器有足够高度 */
	.renew-card :deep(.el-row) {
		min-height: 400px;
		align-items: stretch;
	}

	.renew-card :deep(.el-col) {
		display: flex;
		flex-direction: column;
	}

	/* Your existing styles remain the same */
	.el-radio-button__inner,
	.el-checkbox-button__inner {
		min-width: 120px;
		text-align: center;
	}

	.demo-tabs>.el-tabs__content {
		padding: 32px;
		color: #6b778c;
		font-size: 32px;
		font-weight: 600;
	}

	/* 表单样式调整 */
	.el-form-item {
		margin-bottom: 20px;
	}

	/* 标签靠左对齐 */
	.el-form-item__label {
		display: flex;
		margin-bottom: 8px;
		padding: 0 !important;
		text-align: left !important;
		justify-content: flex-start !important;
	}

	/* 单选按钮组布局 */
	.el-radio-group,
	.el-radio-button-group {
		display: flex;
		flex-wrap: wrap;
	}

	.has-gap {
		gap: 10px;
	}

	.el-radio,
	.el-radio-button {
		margin-right: 0 !important;
	}

	/* 确保标签内容对齐 */
	.form-item-left :deep(.el-form-item__label) {
		display: flex;
		text-align: left;
		justify-content: flex-start;
		font-weight: bold;
	}

	.custom-package-radio {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
	}

	.custom-package-radio :deep(.el-radio-button) {
		margin-right: 0;
		height: auto;
	}

	.custom-package-radio :deep(.el-radio-button__inner) {
		width: 120px;
		min-height: 70px;
		padding: 10px;
		display: block;
		border-radius: 10px !important;
		border: 1px solid #dcdfe6;
		transition: all 0.3s;
		line-height: 1.4;
		text-align: center;
	}

	.package-content {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 100%;
	}

	.package-days {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 4px;
	}

	.package-price {
		font-size: 18px;
		font-weight: bold;
		color: #409eff;
		margin-bottom: 4px;
	}

	.package-discount {
		font-size: 12px;
		color: #999;
		text-decoration: line-through;
	}

	/* 选中状态样式 */
	.custom-package-radio :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner),
	.custom-package-radio :deep(.is-active .el-radio-button__inner) {
		background-color: #f0f7ff !important;
		color: #409eff;
		border-color: #409eff;
		box-shadow: none;
	}

	.custom-package-radio :deep(.is-active .package-days) {
		color: #409eff;
	}

	.custom-package-radio :deep(.is-active .package-price) {
		color: #ff6b00;
	}

	.custom-package-radio :deep(.el-radio-button__inner:hover) {
		border-color: #c6e2ff;
		background-color: #f5f9ff;
	}

	.text-right {
		height: 50px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #d9e2f8;
		padding: 0 20px;

	}

	.content-container {
		position: relative;
		/* min-height: 80vh; */
		display: flex;
		flex-direction: column;
		height: auto;
	}

	/* 标签页容器样式调整 */
	.demo-tabs {
		flex: 1;
		padding-bottom: 20px;
		/* 增加底部内边距 */
	}

	/* 固定在内容区域底部的样式 */
	.footer-container {
		height: 60px;
		background: #d9e2f8;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.footer-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100%;
		padding: 0 20px;
		max-width: calc(100% - 40px);
		/* 防止内容溢出 */
		margin: 0 auto;
		background: #c6e2ff;
	}

	.balance {
		line-height: 32px;
		color: #666;
	}

	.total-section {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.total-section span {
		color: #666;
	}

	/*.el-radio {*/
	/*  margin-bottom: 10px;*/
	/*  width: 100%;*/
	/*}*/

	/*.el-radio :deep(.el-radio__label) {*/
	/*  display: flex;*/
	/*  align-items: center;*/
	/*  width: 100%;*/
	/*}*/

	/* 余额不足提示样式 */
	.balance-insufficient {
		color: #f56c6c;
		font-size: 12px;
		margin-left: 10px;
	}

	.display-between {
		display: flex;
		justify-content: flex-start;
	}

	/* 续费页面样式 */
	.renew-container {
		padding: 20px;
	}

	.renew-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.device-selection {
		margin-bottom: 30px;
	}

	.select-all {
		margin-bottom: 15px;
		padding-left: 0;
		/* 与 el-form-item label 对齐 */
		text-align: left;
		/* 保证 checkbox 内容左对齐 */
	}

	.device-list {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
		gap: 15px;
	}

	.device-card {
		cursor: pointer;
		transition: all 0.3s;
	}

	.device-card.selected {
		border-color: #409EFF;
		background-color: #f0f7ff;
	}

	.device-info {
		display: flex;
		align-items: center;
		gap: 15px;
	}

	.device-details {
		flex: 1;
	}

	.device-model {
		font-weight: bold;
		margin-bottom: 5px;
	}

	.device-id,
	.device-expiry {
		font-size: 12px;
		color: #666;
	}

	.package-selection {
		margin-bottom: 30px;
	}

	.package-options {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
		gap: 15px;
		margin-top: 15px;
	}

	.package-option {
		padding: 10px;
		text-align: center;
	}

	.package-duration {
		font-weight: bold;
		margin-bottom: 5px;
	}

	.package-price {
		color: #409EFF;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.package-daily {
		font-size: 12px;
		color: #999;
	}

	.auto-renew {
		margin-top: 20px;
	}

	.renew-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20px;
		border-top: 1px solid #ebeef5;
	}

	.total-price {
		font-size: 16px;
	}


	/* Add or modify styles for device selection */
	.device-card {
		margin-bottom: 10px;
		cursor: pointer;
		transition: all 0.3s;
	}

	.device-card.selected {
		border-color: #409EFF;
		background-color: #f0f7ff;
	}

	.device-info {
		display: flex;
		align-items: center;
		padding: 10px;
	}

	.device-details {
		margin-left: 10px;
	}

	.device-model {
		font-weight: bold;
		margin-bottom: 5px;
	}

	.device-id,
	.device-expiry {
		font-size: 12px;
		color: #666;
	}

	.renew-footer {
		margin-top: 20px;
		padding-top: 20px;
		border-top: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.price {
		color: #f56c6c;
		font-size: 20px;
		font-weight: bold;
		margin-left: 5px;
	}

	/* Add new styles for the filter section */
	.no-devices {
		padding: 20px;
		text-align: center;
		color: #999;
	}

	/* Make it clear when search is disabled */
	.el-input.is-disabled ::v-deep .el-input__inner {
		background-color: #f5f7fa;
		border-color: #e4e7ed;
		color: #c0c4cc;
		cursor: not-allowed;
	}

	.model-checkbox-row {
		display: flex;
		gap: 12px;
		flex-wrap: wrap;
		align-items: center;
	}

	.model-inline {
		display: flex;
		gap: 12px;
		flex-wrap: wrap;
	}

	.model-inline .el-checkbox {
		margin-right: 0 !important;
	}

	.device-single-col {
		max-height: 400px;
		/* 可视区高度，可自行调整 */
		overflow-y: auto;
		/* 垂直滚动 */
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.device-single-item {
		display: flex;
		align-items: center;
		gap: 10px;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 6px;
		cursor: pointer;
		transition: all 0.2s;
	}

	.device-single-item.selected {
		border-color: #409EFF;
		background: #f0f7ff;
	}

	.device-info {
		flex: 1;
		font-size: 13px;
		line-height: 1.4;
	}

	.no-devices {
		padding: 20px;
		text-align: center;
		color: #999;
	}

	/* 吸底条 */
	.sticky-footer {
		box-sizing: border-box;
		position: absolute;
		bottom: 0;
		right: 0;
		width: 100%;
		height: 60px;
		background: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
		z-index: 999;
	}

	.sticky-footer .total b {
		color: #fa5858;
		font-size: 20px;
	}

	/* 防止内容被吸底条遮住 */
	.device-list {
		padding-bottom: 70px;
	}

	.phone_type_btn_checked {
		background-color: var(--el-button-hover-bg-color);
		border-color: var(--el-button-hover-border-color);
		color: var(--el-button-hover-text-color);
		outline: none;
	}
</style>